package Logic;

import java.util.Random;

public class Board 
{
	/**
	 * Represents cell status: empty, 
	 * under player 1's control or under player 2's control 
	 */
	public enum CellStatus
	{
		Empty(0),
		Player1(1),
		Player2(2);
		
		private int val;
		
		private CellStatus(int val)
		{
			this.val = val;
		}
		
		public static CellStatus getByInt(int val)
		{
			switch (val)
			{
				case 1:
					return Player1;
				case 2:
					return Player2;
				default:
					return Empty;
			}
		}
		
		public int getVal()
		{
			return val;
		}
	}

	class Cell 
	{
		private CellStatus status;
		
		public Cell(CellStatus status)
		{
			setStatus(status);
		}
		
		public CellStatus getStatus()
		{
			return status;
		}
		
		public void setStatus(CellStatus status)
		{
			this.status = status;
		}
	}

	private int size;
	private Cell[][] cells;
	
	private Random rand;
	
	public Board()
	{
		rand = new Random(System.currentTimeMillis());
	}
	
	/**
	 * initialize board
	 * @param boardSize: square board axis length (actual board has boardSize^2 cells)
	 */
	public void initialize(int boardSize)
	{
		size = boardSize;
		cells = new Cell[boardSize][boardSize];

		for (int i = 0; i < boardSize; i++)
		{
			for (int j = 0; j < boardSize; j++)
			{
				cells[i][j] = new Cell(getRandomCellState());
			}
		}
	}
	
	/**
	 * @return size of single axis of board
	 */
	public int getSize()
	{
		return size;
	}
	
	private CellStatus getRandomCellState()
	{
		// we want players to take up only ~40% of the board
		int n = rand.nextInt(6);
		
		switch (n)
		{
			case 1:
				return CellStatus.Player1;
			case 2:
				return CellStatus.Player2;
			default:
				return CellStatus.Empty;
		}
	}
	
	void setCellStatus(int x, int y, CellStatus status)
	{
		if (x < 0 || x >= size ||
		    y < 0 || y >= size)
		{
			return;
		}
		
		cells[x][y].setStatus(status);
	}
	
	/**
	 * Get cell status
	 * @param x: x-coord
	 * @param y: y-coord
	 * @return cell status
	 */
	public CellStatus getCellStatus(int x, int y)
	{
		if (x < 0 || x >= size ||
		    y < 0 || y >= size)
		{
			return null;
		}
		
		return cells[x][y].getStatus();
	}
}
